package com.xianniu.ltc.job;

import cn.devezhao.commons.CalendarUtils;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.rebuild.core.support.ConfigurationItem;
import com.rebuild.core.support.RebuildConfiguration;
import com.rebuild.core.support.integration.QiniuCloud;
import com.rebuild.core.support.mail.IMailService;
import com.rebuild.utils.CommonsUtils;
import com.xianniu.ltc.mapper.TLeadMapper;
import com.xianniu.ltc.model.vo.LeadWeekReportVO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 定期推送周线索给客服部门：上周五-本周四
 * @Author: wangruijie
 * @Date: 2022/16/28 3:26 下午
 */
@Data
@Slf4j
@Component
public class LeadWeekReportJob extends IJobHandler {

    @Value("${LEAD_WEEK_USER}")
    private String leadWeekUser;

    @Resource
    private TLeadMapper leadMapper;
    @Resource
    private IMailService mailService;

//    @XxlJob("leadWeekJobHandler")
    @Override
    @Trace
    public void execute() throws Exception{
        try {
            leadWeekJobHandler();
        } catch (IOException e) {
            XxlJobHelper.handleFail(e.getCause().getMessage());
            e.printStackTrace();
        }
        XxlJobHelper.handleSuccess();
    }

    /**
     * 只推送给指定客服人员线索数据
     * @throws IOException
     */
    public void leadWeekJobHandler() throws IOException {
        String format="yyyy-MM-dd";
        // 客服部门负责邮箱
        String[] email = leadWeekUser.split(",");
        // 昨天时间
        DateTime endTime = DateUtil.yesterday();
        // 一周前时间
        DateTime startTime = DateUtil.lastWeek();
        // 查询线索
        List<LeadWeekReportVO> reportVOS = leadMapper.queryLeadWeek(startTime.toString(format)+" 00:00:00", endTime.toString(format)+" 23:59:59", "standard");
        sendEmail(email, reportVOS, startTime.toString(format), endTime.toString(format));
    }

    /**
     * 获取邮件模板
     * @return
     */
    protected static Element getMailTemplate() {
        String content = CommonsUtils.getStringOfRes("i18n/email.zh_CN.html");
        Assert.notNull(content, "Cannot load template of email");

        Document html = Jsoup.parse(content);
        return html.body();
    }

    /**
     * 组装并发送邮件
     * @param emailAddress
     * @param deptValue
     * @throws IOException
     */
    private void sendEmail(String[] emailAddress, List<LeadWeekReportVO> deptValue, String startTime, String endTime) throws IOException {

        String fileName = "线索数据统计" + startTime + "-" + endTime + ".xlsx";
        File excelFile = new File(fileName);
        ExcelWriter excelWriter = EasyExcel.write(excelFile).build();
        WriteSheet nicheSheet = EasyExcel.
                writerSheet(0, "线索明细").
                head(LeadWeekReportVO.class).
                build();
        excelWriter.write(deptValue, nicheSheet);
        excelWriter.finish();
        String qiniuLink = QiniuCloud.instance().upload(excelFile);
        String downloadUrl = QiniuCloud.instance().url(qiniuLink, "standard");
        // 标题
        String subject = "客服部门 "+ (DateUtil.month(new Date()) + 1) +"月份第" + DateUtil.weekOfMonth(new Date()) +"周线索统计数据";
        String content = "你好！：<p>&#12288;&#12288;请查收" + subject + "</p>";

        Element mailBody = getMailTemplate();

        mailBody.selectFirst(".rb-title").text(subject);
        mailBody.selectFirst(".rb-content").html(content);
        String htmlContent = mailBody.html();
        // 处理公共变量
        htmlContent = htmlContent.replace("%FROM%", "info@xianniu.cn");
        htmlContent = htmlContent.replace("%TIME%", CalendarUtils.getUTCDateTimeFormat().format(CalendarUtils.now()));
        htmlContent = htmlContent.replace("%APPNAME%", RebuildConfiguration.get(ConfigurationItem.AppName));
        htmlContent = htmlContent.replace("%ASKURL%", downloadUrl);
        content = htmlContent;
        mailService.sendHtmlMail(emailAddress, emailAddress, subject, content);
    }
}
